package com.liwenfeng;

import org.springframework.stereotype.Service;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

public class BeanFactory<T> {
    private static final Map<String, Object> singletonBeans = new HashMap<>();

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {


        Pi pi = BeanFactory.getServiceBean(Pi.class);
        System.out.println(pi);
        System.out.println(singletonBeans);
    }

    public T getBean(Supplier<T> supplier) {
        T t = supplier.get();
        T o = (T) singletonBeans.get(t.getClass().getName());
        if (o == null) {
            singletonBeans.put(t.getClass().getName(), t);
            return t;
        }
        return o;
    }

    public static<T> T getServiceBean(Class<T> tClass) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        T t = (T) singletonBeans.get(tClass.getName());
        for (Annotation annotation : tClass.getAnnotations()) {
            if (annotation.annotationType().getName().equals(Service.class.getName())){
                if (t==null){
                    singletonBeans.put(tClass.getName(),tClass.getConstructor().newInstance());
                }
            }
        }
        return (T) singletonBeans.get(tClass.getName());
    }
}
